package com.cjl.learn.singleton.type1;

import org.junit.jupiter.api.Test;
import sun.security.jca.GetInstance;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by Enzo Cotter on 2019-08-06.
 */
public class SingletonTest1 {


    @Test
    public void test1() {
        System.out.println(Singleton1.getInstance() == Singleton1.getInstance());
    }

    @Test
    public void test2() {
        System.out.println(Singleton2.getInstance() == Singleton2.getInstance());
    }

    @Test
    public void test3() {
        System.out.println(Singleton3.getInstance() == Singleton3.getInstance());
    }

    @Test
    public void test4() {
        System.out.println(Singleton4.getInstance() == Singleton4.getInstance());
    }

    @Test
    public void test5() {
        System.out.println(Singleton5.getInstance() == Singleton5.getInstance());
    }

    @Test
    public void test6() {
        System.out.println(Singleton6.getInstance() == Singleton6.getInstance());
    }

    @Test
    public void test7() {
        System.out.println(Singleton7.INSTANCE == Singleton7.INSTANCE);
    }

}

// 饿汉式(静态常量)
class Singleton1 {

    private static final Singleton1 INSTANCE = new Singleton1();

    private Singleton1() {
    }

    public static Singleton1 getInstance() {
        return INSTANCE;
    }
}

// 饿汉式(静态代码块)
class Singleton2 {

    private static Singleton2 INSTANCE;

    private Singleton2() {
    }

    static {
        INSTANCE = new Singleton2();
    }

    public static Singleton2 getInstance() {
        return INSTANCE;
    }
}

// 懒汉式(线程不安全)
class Singleton3 {

    private static Singleton3 INSTANCE;

    private Singleton3() {
    }

    public static Singleton3 getInstance() {
        if (null == INSTANCE) {
            INSTANCE = new Singleton3();
        }
        return INSTANCE;
    }
}


// 懒汉式(线程安全)
class Singleton4 {

    private static Singleton4 INSTANCE;

    private Singleton4() {
    }

    public static synchronized Singleton4 getInstance() {
        if (null == INSTANCE) {
            INSTANCE = new Singleton4();
        }
        return INSTANCE;
    }
}

// 双重检查
class Singleton5 {

    private static volatile Singleton5 INSTANCE;

    private Singleton5() {
    }

    public static Singleton5 getInstance() {
        if (null == INSTANCE) {
            synchronized(Singleton5.class) {
                if (null == INSTANCE) {
                    INSTANCE = new Singleton5();
                }
            }
        }
        return INSTANCE;
    }
}


// 静态内部类
class Singleton6 {

    private Singleton6() {}

    private static class SingletonInstance {
        private static final Singleton6 INSTANCE = new Singleton6();
    }

    public static Singleton6 getInstance() {
        return SingletonInstance.INSTANCE;
    }
}

// 枚举
enum Singleton7 {

    INSTANCE;

    private void test() {
        System.out.println("test...");
    }
}